import {
	Config,
	ComponentSetting
} from "./Config.js"
import UserDataModule from "../model/UserDataModule.js";
import {
	Language
} from "./Language.js"
const _if = {}

_if.getUrlImage = (src, path = "upload/") => {
	return Config.urlBase + path + src;
}

_if.SetUserData = (userDataModule, action = null) => {
	uni.setStorage({
		key: Config.Global_UserInfo,
		data: userDataModule,
		success: () => {
			uni.showToast({
				title: Language.Get("Toast", "LogIn")
			})
			if (action) action();
		}
	})
	uni.setStorageSync(Config.Global_IsLogin, true);
}
//退出登錄
_if.ClearUserData = () => {
	uni.removeStorage({
		key: Config.Global_UserInfo,
		success: () => {
			uni.showToast({
				title: Language.Get("Toast", "LogOut")
			})
		}
	});
	uni.setStorageSync(Config.Global_IsLogin, false);
}

_if.LogOut = (vuePage, action) => {
	_if.ClearUserData();
	vuePage.$shopcart.GetInstance().Clear();
	if (action) action();
}

_if.GetUserData = () => {
	return uni.getStorageSync(Config.Global_UserInfo);
}

_if.GetIsLogin = () => {
	return uni.getStorageSync(Config.Global_IsLogin);
}

_if.SetPlatForm = (platform) => {
	uni.setStorageSync(Config.Global_PlatForm, platform);
}

_if.GetPlatForm = () => {
	return uni.getStorageSync(Config.Global_PlatForm);
}

_if.SetPayment = (payment) => {
	uni.setStorageSync(Config.Global_Payment, payment);
}

_if.GetPayment = () => {
	return uni.getStorageSync(Config.Global_Payment);
}

_if.Initialize = (vuePage) => {
	vuePage.isLoading = vuePage.isLoading || false;

	if (vuePage.isLoading) {
		uni.showLoading({
			title: Language.Get("Toast", "Loading")
		});
	}

	if (!vuePage.hasOwnProperty("GoToPage")) {
		vuePage.GoToPage = (path, page = 'index', switchTab = false, animate = 'none') => {
			if (switchTab) {
				uni.switchTab({
					url: Config.GetPageUrl(path, page)
				})
			} else {
				uni.navigateTo({
					url: Config.GetPageUrl(path, page),
					animationType: animate,
					animationDuration: Config.animationDuration
				});
			}
		}
	}
	if (!vuePage.hasOwnProperty("PageBack")) {
		vuePage.PageBack = (animate = 'pop-out') => {
			uni.navigateBack({
				delta: 1,
				animationType: animate,
				animationDuration: Config.animationDuration
			});
		}
	}
	if (!vuePage.hasOwnProperty("GetTime")) {
		vuePage.GetTime = function() {
			var date = new Date(),
				year = date.getFullYear(),
				month = date.getMonth() + 1,
				day = date.getDate(),
				hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
				minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
				second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
			month >= 1 && month <= 9 ? (month = "0" + month) : "";
			day >= 0 && day <= 9 ? (day = "0" + day) : "";
			var timer = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
			return timer;
		}
	}
}

_if.Initialized = (vuePage, action) => {
	vuePage.isLoading = false;
	if (vuePage.isLoading)
		uni.hideLoading();
	if (!_if.IsNone(action)) action()
}

// 平台检测
_if.TestPlatform = (vuePage) => {
	uni.getProvider({
		service: 'oauth',
		success: function(res) {
			if (~res.provider.indexOf(Config.Platform_QQ)) {
				_if.SetPlatForm(Config.Platform_QQ);
			} else if (~res.provider.indexOf(Config.Platform_WX)) {
				_if.SetPlatForm(Config.Platform_WX);
			} else {
				_if.SetPlatForm(Config.Platform_H5);
			}
			console.log(Language.Get("Debug", "CurrentPlatform", _if.GetPlatForm()));
		}
	});
}

// 用户登录相关
_if.LoginH5 = (url, username, password, action) => {
	uni.showToast({
		title: Language.Get("Toast", "LoadingUserData")
	})
	return uni.request({
		url: url,
		method: "POST",
		data: {
			"username": username,
			'password': password
		},
		success: (res) => {
			if (res.data.code === 1) {
				let userData = new UserDataModule(
					res.data.data['id'],
					res.data.data['user_login'],
					res.data.data['user_nickname'],
					res.data.data['avatar'],
					res.data.data['token']
				);
				_if.SetUserData(userData);
				action && action(res);
			}
			uni.showToast({
				title: res.data.msg
			})
		}
	})
}

_if.LoginWX = (url, code, userInfo, action) => {
	uni.showToast({
		title: Language.Get("Toast", "LoadingUserData")
	})
	let _code = {
		"code": code
	};
	let data = _if.MegaJson([_code, userInfo]);
	return uni.request({
		url: url,
		method: "POST",
		data: data,
		success: (res) => {
			// console.log(res);
			if (res.data.code === 1) {
				let data = res.data.data;
				let user = data.user;
				let _user_data = new UserDataModule(user.id, user.user_login, user.user_nickname, data.token);
				_if.SetUserData(_user_data);
				if (action) action(res);
			}
			uni.showToast({
				title: res.data.msg
			})
		}
	})
}

_if.NeedLogin = (vuePage, wait = 0) => {
	if (_if.GetIsLogin())
		return;
	uni.showToast({
		title: Language.Get("Toast", 'NeedLogin')
	})
	if (!wait) {
		vuePage.GoToPage("user", "login")
		return;
	}
	vuePage.$_if.IntervalOnce(() => {
		vuePage.GoToPage("user", "login")
	}, wait)
}

// 支付相关
_if.PaymentPlatform = () => {
	uni.getProvider({
		service: 'payment',
		success: function(res) {
			if (~res.provider.indexOf(Config.Payment_ALI)) {
				_if.SetPayment(Config.Payment_ALI);

				uni.requestPayment({
					provider: _if.GetPayment(),
					orderInfo: 'orderInfo', //微信、支付宝订单数据
					success: function(res) {
						console.log('success:' + JSON.stringify(res));
					},
					fail: function(err) {
						console.log('fail:' + JSON.stringify(err));
					}
				});

			} else if (~res.provider.indexOf(Config.Payment_WX)) {
				_if.SetPayment(Config.Payment_WX);

				uni.requestPayment({
					provider: _if.GetPayment(),
					timeStamp: String(Date.now()),
					nonceStr: 'A1B2C3D4E5',
					package: 'prepay_id=wx20180101abcdefg',
					signType: 'MD5',
					paySign: '',
					success: function(res) {
						console.log('success:' + JSON.stringify(res));
					},
					fail: function(err) {
						console.log('fail:' + JSON.stringify(err));
					}
				});

			} else {
				_if.SetPayment(Config.Payment_H5);
			}

			console.log(Language.Get("Debug", "CurrentPayment", _if.GetPayment()));

		}
	});
}

// 网络
_if.Http = (options) => {
	return uni.request({
		url: Config.GetUrl(options.url),
		method: options.method || "GET",
		data: options.data || {},
		success: res => {
			if (res.data.code !== 0) {
				if (options.toast)
					uni.showToast({
						title: Language.Get('Toast', "SuccessTitle"),
						duration: ComponentSetting.Toast.delaytime,
						icon: "success"
					});
				if (options.hasOwnProperty("success"))
					options.success(res.data)
			} else {
				if (options.toast)
					uni.showToast({
						title: Language.Get('Toast', "FailTitle"),
						duration: ComponentSetting.Toast.delaytime,
						icon: "none"
					});
				if (options.hasOwnProperty("fail"))
					options.fail(res)
			}

		},
		fail: error => {
			if (options.toast)
				uni.showToast({
					title: Language.Get('Toast', "ErrorTitle"),
					duration: ComponentSetting.Toast.delaytime,
					icon: "none"
				});
			if (options.hasOwnProperty("error"))
				options.error(error)
		},
		complete: res => {
			if (options.hasOwnProperty("complete"))
				options.complete(res)
		}
	})
}

// swiper 设置
_if.ResetSwiperSetting = (vuePage) => {
	vuePage.indicatorDots = ComponentSetting.Swiper.indicatorDots;
	vuePage.autoPlay = ComponentSetting.Swiper.autoPlay;
	vuePage.duration = ComponentSetting.Swiper.duration;
	vuePage.interval = ComponentSetting.Swiper.interval;
	vuePage.circular = ComponentSetting.Swiper.circular;
	vuePage.indicatorActiveColor = ComponentSetting.Swiper.indicatorActiveColor;
	vuePage.indicatorColor = ComponentSetting.Swiper.indicatorColor;
	vuePage.swiperImageMode = ComponentSetting.Swiper.imageMode;
}

// page 设置
_if.PageInitialize = (vuePage, maxPage = Config.maxPage, minPage = Config.minPage, pageClip = Config.pageClip) => {
	vuePage.currentPage = vuePage.currentPage || Config.initCurrentPage;
	vuePage.minPage = vuePage.minPage || minPage;
	vuePage.maxPage = vuePage.maxPage || maxPage;
	vuePage.pageClip = vuePage.pageClip || pageClip;
	vuePage.pageOver = false;
}

_if.pageIncrese = (vuePage, incressAction, pageClip = vuePage.pageClip) => {
	vuePage.currentPage += pageClip;
	if (vuePage.maxPage) {
		if (vuePage.currentPage > vuePage.maxPage) {
			vuePage.currentPage = vuePage.maxPage;
			vuePage.pageOver = true;
		} else {
			incressAction()
		}
	}
};

_if.pageReduce = (vuePage, reduceAction, pageClip = vuePage.pageClip) => {
	vuePage.currentPage -= pageClip;
	if (vuePage.currentPage <= vuePage.minPage) {
		vuePage.currentPage = vuePage.minPage;
	} else {
		reduceAction()
	}
};

_if.OnReachBottom = (vuePage, action, overAction, pageClip = vuePage.pageClip) => {
	_if.pageIncrese(vuePage, action, pageClip);
	if (vuePage.pageOver && !_if.IsNone(overAction))
		overAction()
}


// 公用方法
_if.ListAddItem = (list, items) => {
	return [...list, ...items]
}

// 判断空值
_if.IsNone = (parm) => {
	if (parm == "" || parm == "undefined" || parm == null)
		return true
	return false
}

// 数据拷贝
_if.Copy = (obj) => {
	_obj = JSON.stringify(obj);
	return JSON.parse(_obj);
}

// 间隔执行1次
_if.IntervalOnce = (func, time) => {
	let interval = setInterval(function() {
		func();
		clearInterval(interval);
	}, time);
}

// 间隔执行n次
_if.IntervalLoop = (func, time, loop = 2) => {
	let interval = setInterval(function() {
		func();
		loop -= 1
		if (loop <= 0)
			clearInterval(interval);
	}, time);
}

_if.MegaJson = (...args) => {
	let json = args[0][0];
	if (args.length > 0)
		for (let i = 0; i < args.length; i++) {
			for (let j = 1; j < args[i].length; j++) {
				json = JSON.parse((JSON.stringify(json) + JSON.stringify(args[i][j])).replace(/}{/, ','));
			}
		}
	return json;
}

// 金钱转化
_if.Price = (price, round = true) => {
	price = price.toFixed(2);
	if (round)
		while (price.substr(price.length - 1, 1) == '0' || price.substr(price.length - 1, 1) == '.')
			price = price.substr(0, price.length - 1)
	return price;
}

_if.GetOfferDate = (offer_day = 7, postfix = "-", is_mouth = false) => {
	let date1 = new Date();
	let time1 = date1.getFullYear() + "-" + (date1.getMonth() + 1) + "-" + date1.getDate();
	let date2 = new Date(date1);
	date2.setDate(date1.getDate() + offer_day);
	let day = date2.getDate() < 10 ? "0" + date2.getDate() : date2.getDate()
	let mouth = (date2.getMonth() + 1) < 10 ? "0" + (date2.getMonth() + 1) : (date2.getMonth() + 1)
	let time2 = ""
	if (!is_mouth) time2 = date2.getFullYear() + postfix + mouth + postfix + day;
	else time2 = date2.getFullYear() + postfix + mouth;
	return time2;
}

_if.FormatThumb = (format_list , http_url , key_code="imageUrl") => {
	let list = []
	for(let i = 0 ; i < format_list.length;i++){
		let item = format_list[i];
		item[key_code] = http_url + item[key_code];
	}
	return list;
}
export {
	_if
}
